package com.app.qbake.module.square;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.app.qbake.util.GalleryHelper;
import com.netease.nim.uikit.api.NimUIKit;
import com.wind.base.mvp.view.BaseLoadingFragment;
import com.wind.base.repo.UserRepo;
import com.wind.base.request.BaseRequest;
import com.wind.base.utils.ViewInflater;
import com.wind.coder.annotations.Api;
import com.wind.coder.annotations.Heros;
import com.wind.coder.annotations.Param;
import com.wind.data.msg.GoodsChatResponse;
import com.wind.data.square.CollectOpResponse;
import com.wind.data.square.GoodsDetailRequest;
import com.wind.data.square.GoodsDetailResponse;
import com.wind.data.square.bean.Goods;
import com.wind.data.square.bean.Pic;
import com.app.qbake.R;
import com.app.qbake.module.login.LoginActivity;
import com.app.qbake.module.mine.activity.VipPkgActivity;
import com.app.qbake.module.msg.layout.GoodsChatLayout;
import com.app.qbake.module.square.activity.OrderDetailActivity;
import com.app.qbake.module.square.activity.SellerHomeActivity;
import com.app.qbake.module.square.di.GoodsDetailComponent;
import com.app.qbake.module.square.layout.CollectOpLayout;
import com.app.qbake.module.square.mvp.GoodsDetailView;
import com.app.qbake.module.square.presenter.GoodsDetailPresenter;
import com.app.qbake.util.AppDialogHelper;
import com.app.qbake.util.MediaUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

@Heros(
        param = @Param(
                viewCanonicalName = "com.app.qbake.module.square.mvp.GoodsDetailView",
                responseCanonicalName = "com.wind.data.square.GoodsDetailResponse",
                requestCanonicalName = "com.wind.data.square.GoodsDetailRequest"
        ),
        api = @Api(httpMethod = Api.HttpMethod.GET, url = "shop/details")
)
public class GoodsDetailFragment extends BaseLoadingFragment<GoodsDetailView, GoodsDetailPresenter, GoodsDetailComponent, GoodsDetailResponse>
        implements GoodsDetailView, CollectOpLayout.OnCollectListener, GoodsChatLayout.OnGoodsChatListener {
    public static final String ARGS_KEY_GOODS_ID = "args_key_goods_id";
    private String mGoodsId;
    private Goods mGoods;

    @BindView(R.id.iv_avatar)
    ImageView iv_avatar;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_lasttime)
    TextView tv_lasttime;
    @BindView(R.id.tv_price)
    TextView tv_price;
    @BindView(R.id.tv_content)
    TextView tv_content;
    @BindView(R.id.view_pager)
    ViewPager view_pager;

    @BindView(R.id.tv_percent)
    TextView tv_percent;

    @BindView(R.id.tv_collect)
    TextView tv_collect;
    @Inject
    GoodsDetailPresenter presenter;
    ImagePagerAdapter mAdapter;

    CollectOpLayout mCollectOpLayout;

    GoodsChatLayout mGoodsChatLayout;
    @Override
    public GoodsDetailPresenter createPresenter() {
        return presenter;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mGoodsId = getArguments().getString(ARGS_KEY_GOODS_ID);
        super.onViewCreated(view, savedInstanceState);
        mCollectOpLayout=new CollectOpLayout(getActivity(),this);
        mGoodsChatLayout=new GoodsChatLayout(getActivity(),this);
        mAdapter = new ImagePagerAdapter();
        view_pager.setAdapter(mAdapter);
        view_pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int p = position + 1;
                tv_percent.setText(p + "/" + mAdapter.items.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected BaseRequest buildLoadingRequest() {
        GoodsDetailRequest request = new GoodsDetailRequest();
        request.setGoodsId(mGoodsId);
        return request;
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_goods_detail;
    }

    @Override
    public void showPage(GoodsDetailResponse reponse) {
        mGoods = reponse.getData();
        ViewInflater.inflateText(tv_lasttime, mGoods.getLast_login_time()+"活跃");
        ViewInflater.inflateImage(iv_avatar, mGoods.getAvatar());
        ViewInflater.inflateText(tv_name, mGoods.getUserName());
        ViewInflater.inflateText(tv_price, "￥" + mGoods.getPrice());
        ViewInflater.inflateText(tv_content, mGoods.getTitle());
        List<Pic> pics = new ArrayList<>();
        if (mGoods.getIs_video() == Goods.CODE_YES && !TextUtils.isEmpty(mGoods.getVideo_image())) {
            Pic video = new Pic(mGoods.getVideo_image());
            video.setVideoCover(true);
            video.setVideoUrl(mGoods.getVideo_url());
            pics.add(video);
        }
        List<String> urls = mGoods.getImages_url();

        for (String url : urls) {
            pics.add(new Pic(url));
        }
        mAdapter.add(pics);
        tv_percent.setText(1 + "/" + mAdapter.items.size());
        mLayoutManager.showContent();

        if (mGoods.getIs_collect()==1){
            //收藏操作
            tv_collect.setText("已收藏");
            tv_collect.setTextColor(Color.parseColor("#ED705D"));
        }else if (mGoods.getIs_collect()==0){
            //取消收藏操作
            tv_collect.setText("收藏");
            tv_collect.setTextColor(Color.parseColor("#333333"));
        }


    }

    public Goods getGoods(){
        return mGoods;
    }
    public static GoodsDetailFragment newInstance(String goodsId) {
        GoodsDetailFragment f = new GoodsDetailFragment();
        Bundle args = new Bundle();
        args.putString(ARGS_KEY_GOODS_ID, goodsId);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCollectReturn(CollectOpResponse response) {
        if (response.getType().equals(CollectOpLayout.TYPE_C)){
            mGoods.setIs_collect(1);
            //收藏操作
            tv_collect.setText("已收藏");
            tv_collect.setTextColor(Color.parseColor("#ED705D"));
        }else if (response.getType().equals(CollectOpLayout.TYPE_UC)){
            //取消收藏操作
            mGoods.setIs_collect(0);
            tv_collect.setText("收藏");
            tv_collect.setTextColor(Color.parseColor("#333333"));
        }
    }

    @Override
    public void onGoodsChatSuccess(GoodsChatResponse response) {
        if ("yes".equals(response.getData().getChat())){
             NimUIKit.startP2PSession(getActivity(), mGoods.getUserId());
        }else {
            AppDialogHelper.showNormalDialog(getActivity(),
                    "只有VIP才能聊天", "取消", "开通", new AppDialogHelper.DialogOperCallback() {
                        @Override
                        public void onDialogConfirmClick() {

                            VipPkgActivity.start(getActivity());
                        }
                    });
        }
    }


    private class ImagePagerAdapter extends PagerAdapter {
        private List<Pic> items;

        public ImagePagerAdapter() {
            this.items = new ArrayList<>();
        }

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // super.destroyItem(container, position, object);
            container.removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            View view = getActivity().getLayoutInflater().inflate(R.layout.item_goods_pic, container, false);
            //最后要返回的是控件本身
            ImageView iv = view.findViewById(R.id.iv);
            ImageView iv_video = view.findViewById(R.id.iv_video);
            ViewInflater.inflateImage(iv, items.get(position).getUrl());
            final Pic pic = items.get(position);
            if (items.get(position).isVideoCover()) {
                iv_video.setVisibility(View.VISIBLE);
            } else {
                iv_video.setVisibility(View.GONE);
            }
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (pic.isVideoCover()) {
                        //检查是否登录
                        if (UserRepo.getInstance().isLogin(getActivity())) {

                            boolean isVip = UserRepo.getInstance().isVip(getActivity());
                            if (isVip) {
                                //查看视频
                                // VideoPlayerActivity.start(getActivity(),pic.getVideoUrl());
                                MediaUtil.startVideoPlayer(getActivity(),pic.getVideoUrl());
                            } else {
                                //TODO 提示会员弹窗
                                AppDialogHelper.showNormalDialog(getActivity(),
                                        "只有VIP才能观看视频", "取消", "开通", new AppDialogHelper.DialogOperCallback() {
                                    @Override
                                    public void onDialogConfirmClick() {

                                        VipPkgActivity.start(getActivity());
                                    }
                                });
                            }
                        } else {
                            LoginActivity.start(getActivity());
                        }
                    } else {
                        //TODO 照片预览
                        GalleryHelper.preview(getActivity(),items,position);
                    }
                }
            });
            container.addView(view);
            return view;
        }


        public void add(List<Pic> pics) {
            items.addAll(pics);
            notifyDataSetChanged();
        }
    }

    @OnClick({R.id.layout_collect,R.id.layout_chat,R.id.tv_buy,R.id.iv_avatar})
    public void onViewClick(View view){
        switch (view.getId()){
            case R.id.iv_avatar:
                SellerHomeActivity.start(getActivity(),mGoods.getUserId());
                break;
            case R.id.tv_buy:
                //检查是否登录
                if (UserRepo.getInstance().isLogin(getActivity())) {
                    //检查是否已登录
                    OrderDetailActivity.start(getActivity(),mGoods);
                }else {
                    LoginActivity.start(getActivity());
                }

                break;
            case R.id.layout_collect:

                if (UserRepo.getInstance().isLogin(getActivity())) {
                    int collectCode=mGoods.getIs_collect();
                    if (collectCode==0){
                        mCollectOpLayout.collect(mGoods.getUserId(),mGoods.getId());
                    }else {
                        mCollectOpLayout.uncollect(mGoods.getUserId(),mGoods.getId());
                    }

                }else {
                    LoginActivity.start(getActivity());
                }


                break;
            case R.id.layout_chat:
                if (UserRepo.getInstance().isLogin(getActivity())) {
                    //是否是会员
                    mGoodsChatLayout.goodsChat(mGoodsId,mGoods.getUserId());

                }else {
                    LoginActivity.start(getActivity());
                }

                break;
        }
    }
}
